package com.haima.sage.bigdata.api.service.impl;

import com.haima.sage.bigdata.api.dao.AuditLogRepository;
import com.haima.sage.bigdata.api.entity.auditlog.AuditLog;
import com.haima.sage.bigdata.api.service.AuditLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Service
public class AuditLogServiceImpl implements AuditLogService {
    private final AuditLogRepository auditLogRepository;

    @Autowired
    public AuditLogServiceImpl(AuditLogRepository auditLogRepository) {
        this.auditLogRepository = auditLogRepository;
    }

    @Transactional(readOnly = false)
    @Override
    public void save(AuditLog auditLog) {
        if (auditLog.getId() == null) {
            auditLog.setId(UUID.randomUUID().toString().replace("-", ""));
        }
        if (auditLog.getCreateDate() == null) {
            auditLog.setCreateDate(new Date());
    }
        this.auditLogRepository.save(auditLog);
    }

    @Transactional(readOnly = true)
    @Override
    public Optional<AuditLog> findById(String id) {
        return this.auditLogRepository.findById(id);
    }

    @Transactional(readOnly = true)
    @Override
    public Page<AuditLog> findAll(Specification<AuditLog> query, Pageable pageable) {
        return this.auditLogRepository.findAll(query, pageable);
    }
}
